#include "BulletManager.h"

Bullet::Bullet() : Entity(){}
Bullet::~Bullet(){
}

void Bullet::render(){
	if(!isActive) return;
	glPushMatrix();
	model.set();
	
	//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glLineWidth(2.0);
	
	//glEnable(GL_BLEND);
	glBegin(GL_LINES);
		glColor4f(1,1,0,1);
		//Vector3 center = model*Vector3();
		Vector3 center = Vector3();
		//Vector3 point2 = model*Vector3(0,-100,0);
		Vector3 point2 = Vector3(0,10,0);
		glVertex3f(center.x,center.y,center.z);
		glColor4f(1,1,0,0);
		//Vector3 lineEnd = (model*speed).normalize()*-10;
		glVertex3f(point2.x, point2.y, point2.z);
	glEnd();
	//glDisable(GL_BLEND);
	glPopMatrix();
	glColor3f(1,1,1);
}

void Bullet::update(float dt){
	timeLeft -= dt;
	if(timeLeft <= 0){
		isActive = false;
		return;
	}
	Vector3 dpos = speed * dt;
	model.traslateLocal(dpos.x, dpos.y, dpos.z);
	//speed = speed + acceleration*dt;

}

bool Bullet::collides(EntityMesh* ent){
	
	float segmentLength = 20;
	//Vector3 dir = speed.normalize();
	//Vector3 origin = Vector3() - dir*segmentLength;

	Vector3 dir = (model*speed).normalize();
	Vector3 origin = model*Vector3() - dir*segmentLength;

	ent->mesh->collision_model->setTransform(ent->model.m);
	if(ent->segmentCollision(origin, dir,0,segmentLength)){
		isActive = false;
		return true;
	}
	return false;

}


void BulletManager::shootBullet(Matrix44 m, Vector3 speed){
	Bullet* b = new Bullet();
	b->model = m;
	b->speed = speed;
	b->timeLeft = 10;
	b->isActive = true;
	bullets.push_back(b);

}

BulletManager::BulletManager(void)
{
}


BulletManager::~BulletManager(void)
{
}

BulletManager* BulletManager::getInstance(){
	if (instance == NULL)
		instance = new BulletManager();
	return instance;
}

void BulletManager::update(float dt){
	std::list<Bullet*>::iterator it = bullets.begin();
	while(it != bullets.end()){
		(*it)->update(dt);
		if((*it)->isActive) it++;
		else{
			delete (*it);
			it = bullets.erase(it);
		}
	}
}

void BulletManager::render(){
	
	for(std::list<Bullet*>::iterator it = bullets.begin(); it != bullets.end(); ++it){
		(*it)->render();
	}
}

int BulletManager::collides(EntityMesh* ent){
	int collisions = 0;
	std::list<Bullet*>::iterator it = bullets.begin();
	while( it != bullets.end()){
		if((*it)->collides(ent)){
			delete (*it);
			it = bullets.erase(it);
			++collisions;
		}
		else ++it;
	}
	return collisions;
}


BulletManager* BulletManager::instance = NULL;
